var app = angular.module("cdf91680",[]);

/**
* Define the root scope for each controller onn the application
* 
* Need to manage translations and current user
*/
app.run(function($rootScope) 
{
	$rootScope.translations = undefined;
	
    $rootScope.currentUser = undefined;

	/**
	* Set the current user
	*/
	$rootScope.setCurrentUser = function(data)
	{
		console.info("setCurrentUser - called with data : " + data); 
		
		try
		{
			if(typeof(Storage) !== undefined) 
			{
				localStorage.setItem("CurrentUser", JSON.stringify(data));
			} 
			else 
			{
				$cookieStore.put("CurrentUser", JSON.stringify(data));
			}
		}
		catch(exception)
		{
			console.error(exception.message);
		}
		$rootScope.currentUser = data;
	};
	
	/**
	* Get the current user
	*/
	$rootScope.getCurrentUser = function()
	{
		try
		{
			if(typeof(Storage) !== "undefined") 
			{
				$rootScope.currentUser = JSON.parse(localStorage.getItem("CurrentUser"));
			} 
			else 
			{
				$rootScope.currentUser = JSON.parse($cookieStore.get('CurrentUser'));
			}
		}
		catch(err)
		{
			$rootScope.currentUser = undefined;
		}
		return $rootScope.currentUser;
	};
	
	/**
	* Destroy the current user
	*/
	$rootScope.removeCurrentUser = function()
	{
		console.info("removeCurrentUser - called"); 
		if(typeof(Storage) !== undefined) 
		{
			$rootScope.currentUser = localStorage.removeItem("CurrentUser");
		} 
		else 
		{
			$rootScope.currentUser = $cookieStore.remove('CurrentUser');
		}
		$rootScope.$broadcast('currentUser', {
		  user: undefined 
		});
		$rootScope.currentUser = undefined;
	};
});

app.controller("maincontroller", ['$scope', '$parse', '$http', '$rootScope', function($scope, $parse, $http, $rootScope) 
{
	$scope.servicebase = '../../Core/server.class.php';
	
	console.info("Set default variables");
	$scope.messageVisible = false;
	$scope.isBodyLoading = true;
	$scope.isAuthenticate = false;
	$scope.tchatMessages = [];
	$scope.tchatMessagesIds = [];
	$scope.lastTchatMessageId = 0;
	$scope.isMessageSending = false;
	angular.module('cdf91680', ['ngCookies']);
	
	/**
	* Set a user message
	*/
	$scope.authenticateCommand = function(login, password, isAlreadySHA)
	{	
		console.info("authenticateCommand called - " + login + " / " + password);
		$scope.isAuthenticating = true;
		
		if(isAlreadySHA == undefined)
		{ 
			password = sha1(password);
		}
		
		console.info(password);
		$http.post($scope.servicebase, { "service" : "authenticate", "login" : login, "password" : password}).
		success(function(data, status) 
		{
			console.info("authenticateCommand - call success"); 
			$scope.data = data;
			$scope.result = data;
			if($scope.data.isFailed == true)
			{
				$scope.isAuthenticate = false;
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				$scope.isAuthenticate = true;
				$rootScope.setCurrentUser(data.response);
				$("#authenticate").modal('hide');
			}
			
			$scope.isAuthenticating = false;
		})
		.
		error(function(data, status) 
		{
			console.error("authenticateCommand - call failed"); 	
			$scope.data = data || "Request failed";
			$scope.isBodyLoading = false;
			$scope.isAuthenticating = false;
			console.error("authenticateCommand - data : " + $scope.data);		
		});
	};
	
	/**
	* Logout from cdf91680
	*/
	$scope.logoutCommand = function()
	{
		if($rootScope.getCurrentUser() != undefined)
		{
			$scope.isAuthenticate = false;
			$http.post($scope.servicebase, { "service" : "setUserAsOffline", "userid" : $rootScope.currentUser.Id}).
			success(function(data, status) 
			{
				console.info("setUserAsOffline - call success"); 
				$rootScope.removeCurrentUser();
			})
			.
			error(function(data, status) 
			{
				console.error("setUserAsOffline - call failed"); 	
			});
		}
	};
	
	/**
	* Root on admin
	*/
	$scope.personalSpaceCommand = function()
	{
		$(location).attr('href',"admin.html");
	};
	

	
	/**
	* Set a user message
	*/
	$scope.setMessageCommand = function(message, type, area)
	{	
		console.info("setMessageCommand called - " + message + " on area : " + area);
		
		var container = '';
		
		if(area == undefined || area == '')
		{
			container = '#messageManager';
			$scope.messageVisible = true;
		}
		else
		{
			container = "#" + area;
		}
		$(container).show();
		
		$scope.messageType = type;
		$scope.messageLabel = message;

		setTimeout
		(
			function()
			{
				$(container).hide();
			}
		, 4000
		);
	};
	
	/**
	* Get url parameter
	*/
	$scope.GetURLParameter = function(sParam)
	{
	    var sPageURL = window.location.search.substring(1);
	    var sURLVariables = sPageURL.split('&');
	    for (var i = 0; i < sURLVariables.length; i++)
	    {
	        var sParameterName = sURLVariables[i].split('=');
	        if (sParameterName[0] == sParam)
	        {
	            return sParameterName[1];
	        }
	    }
		
		return undefined;
	};

	/**
	* Get main translations
	*/
	$scope.getMainTranslationsCommand = function()
	{
		console.info("getMainTranslationsCommand called");
		
		if($scope.GetURLParameter('error') != undefined && $scope.GetURLParameter('error') == 'auth')
		{
			console.info("User have to be authenticate");
			$("#authenticate").modal('show');
			$scope.setMessageCommand('Vous devez vous authentifier', 'danger', 'authentificationMessage');
		}
		
		//Check user authorization
		if($rootScope.getCurrentUser() == undefined)
		{
			var urlPage = window.location.href.split("/")[window.location.href.split("/").length - 1].split(".")[0];
			
			if(urlPage == "admin" || urlPage == "accounting" || urlPage == "data" || urlPage == "documents" || urlPage == "settings")
			{
				console.info("User is not allow to go here");
				$(location).attr('href',"index.html?error=auth");
			}
		}
	
		$http.post($scope.servicebase, { "service" : "getTranslations"}).
		success(function(data, status) 
		{
			console.info("getMainTranslationsCommand - call success"); 
			$scope.status = status;
			if(data.isFailed == true)
			{
				$scope.setMessageCommand($scope.data.exception, 'danger');
			}
			else
			{
				for (key in data.response) {
					if (data.response.hasOwnProperty(key)) 
					{
						var model = $parse(key);
						model.assign($scope, data.response[key]);
						if (!$scope.$$phase && !$scope.$root.$$phase){
							$scope.$apply();
						}
					}
				}   
				
				$scope.$broadcast('translations', {
					translations: data 
				});
				$rootScope.translations = data;
			}
			$scope.isBodyLoading = false;
		})
		.
		error(function(data, status) 
		{	
			console.error("getMainTranslationsCommand - call failed"); 	
			$scope.status = status;
			$scope.isBodyLoading = false;
			console.error("getMainTranslationsCommand - data : " + $scope.data);		
		});
	};
	
	/**
	 * Send a new message
	 */
	$scope.sendTchatMessagesCommand = function()
	{
		$scope.isMessageSending = true;
		console.info("sendTchatMessagesCommand called with : " + $scope.newTchatMessage);
		$http.post($scope.servicebase, { "service" : "addTchatMessage", "message" : $scope.newTchatMessage, "user" : $rootScope.currentUser.Id }).
		success(function(data, status) 
		{
			console.info("checkNewTchatMessagesCommand - call success"); 
			$scope.newTchatMessage = '';
			$scope.isMessageSending = false;
		})
		.
		error(function(data, status) 
		{
			$scope.isMessageSending = false;
			$scope.setMessageCommand('Serveur de tchat KO', 'danger');
		});
	};
	
	/**
	* Check the server status
	*/
	$scope.checkServerStateCommand = function()
	{
		$http.post($scope.servicebase, { "service" : "IsServerAvailable"}).
		success(function(data, status) 
		{
			//console.info("checkServerStateCommand - call success"); 
		})
		.
		error(function(data, status) 
		{
			console.error("checkServerStateCommand - the server is not available : " + status); 	
			$scope.setMessageCommand('Le serveur n\'est pas disponible', 'danger');
		});
	};

	$scope.getMainTranslationsCommand();
	
	//Check the current user status
	$rootScope.currentUser = $rootScope.getCurrentUser();
	
	if($rootScope.currentUser != undefined)
	{
		$scope.authenticateCommand($rootScope.currentUser.Login, $rootScope.currentUser.Password, true);
	}
	
	//Check if server is available
	setInterval(function()
	{
		$scope.checkServerStateCommand();
	}, 5000);
}]);